﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
using Microsoft.Win32;
using System.Data;



namespace QuickWPFMonthCalendar
{
    /// <summary>
    /// Create.xaml の相互作用ロジック
    /// </summary>
    public partial class Create : Window
    {
        private bool isEdit = false;
        private DB.Tables.Settings Settings = new DB.Tables.Settings();

        public Create(string srt = "")
        {

            InitializeComponent();

            if (string.IsNullOrEmpty(srt))
                this.btnTitle.Text = Const.GetToDay;
            else
                this.btnTitle.Text = srt;


            IsExist();

            GetSettings();

            bg.Source = returnImageBib(string.Format("/MyDiary;component/Images/{0}.jpg", Settings.color));
        }

        private void IsExist()
        {
            isEdit = false;
            var execute = new DB.Execute();
            DateTime dtDateFormat = DateTime.Parse(this.btnTitle.Text.ToString());
            DataSet ds = execute.Select_tblBody(dtDateFormat);

            foreach (DataTable dt in ds.Tables)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    this.txbBody.Text = dr["Body"].ToString();

                    DataSet dsImages = execute.Select_tblImages(int.Parse(dr["Id"].ToString()));
                    foreach (DataTable dtImages in dsImages.Tables)
                    {
                        foreach (DataRow drImages in dtImages.Rows)
                        {
                            string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);


                            Image img = new Image();
                            img.Width = 90;
                            img.Height = 90;
                            returnImage(ref img, path + @"\" + drImages["Path"].ToString());

                            this.lstImage.Items.Add(img);
                        }
                    }

                    isEdit = true;
                }

            }

            if (!isEdit)
            {
                this.lstImage.Items.Clear();

                btnDelete.Visibility = Visibility.Hidden;
            }
        }

        protected BitmapImage returnImageBib(string path)
        {

            BitmapImage bitImage = new BitmapImage();
            bitImage.BeginInit();
            Uri uri = new Uri(path, UriKind.RelativeOrAbsolute);
            bitImage.UriSource = uri;
            bitImage.EndInit();

            return bitImage;
        }

        private void lstImage_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //TextBlock tx = (TextBlock)lstImage.SelectedItem;

            //string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);


            //BitmapImage bitImage = new BitmapImage();
            //bitImage.BeginInit();
            //Uri uri = new Uri(string.Format(path+@"\2012\{0}.png", tx.Text), UriKind.RelativeOrAbsolute);
            //bitImage.UriSource = uri;
            //bitImage.EndInit();

            // imgView.Source = bitImage ;
        }


        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "(*.jpg)|*.jpg|(*.png)|*.png|(*.bmp)|*.bmp";
            dialog.Multiselect = true;
            dialog.InitialDirectory = Const.DefaultPathDirectory;
            dialog.Title = "Log File";

            Nullable<bool> result = dialog.ShowDialog();
            if (result.Value)
            {
                string[] files = dialog.FileNames;
                foreach (string sfile in files)
                {
                    Image img = new Image();
                    img.Width = 90;
                    img.Height = 90;
                    returnImage(ref img, sfile);

                    this.lstImage.Items.Add(img);

                    //chFiles.Items.Add(sfile);
                    //pathDirectory = Path.GetDirectoryName(sfile);
                }
            }

        }

        protected void returnImage(ref Image img, string path)
        {
            BitmapImage bitImage = new BitmapImage();
            bitImage.BeginInit();
            Uri uri = new Uri(string.Format(path), UriKind.RelativeOrAbsolute);
            bitImage.UriSource = uri;
            bitImage.EndInit();
            img.Source = bitImage;
            img.Stretch = Stretch.Uniform;
        }


        protected string returnImagePath(Image img)
        {
            BitmapImage bitImage = (BitmapImage)img.Source;
            return CopyImage(bitImage.UriSource.LocalPath);


        }

        private void btnTitle_Click(object sender, RoutedEventArgs e)
        {

            // this.txbTitle.Text = Const.GetToDay;
            // this.txbTitle.Visibility = Visibility.Visible;
            popup1.IsOpen = true;

        }

        private void clrDate_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
        {
            popup1.IsOpen = false;
            this.btnTitle.Text = clrDate.SelectedDate.Value.ToString(Const.JapaneseFormatDate);
            IsExist();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            var execute = new DB.Execute();

            DateTime dtDateFormat = DateTime.Parse(this.btnTitle.Text.ToString());

            List<DB.Tables.Diary> list = new List<DB.Tables.Diary>();
            var item = new DB.Tables.Diary
            {
                Body = this.txbBody.Text,
                DateFormat = dtDateFormat.ToString()
            };

            list.Add(item);

            if (isEdit)
                execute.Update_tblBody(list);
            else
                execute.Insert_tblBody(list);

            if (execute._error.Count > 0)
            {
                showMessage(execute._error);
                return;
            }

            var ds = execute.Select_tblBody(dtDateFormat);
            if (execute._error.Count > 0)
            {
                showMessage(execute._error);
                return;
            }

            foreach (DataTable dt in ds.Tables)

                foreach (DataRow dr in dt.Rows)
                {

                    var listImages = new List<DB.Tables.Images>();
                    foreach (var items in this.lstImage.Items)
                    {
                        Image img = (Image)items;

                        var itemImage = new DB.Tables.Images
                        {
                            Id_diary = dr["Id"].ToString(),
                            Path = returnImagePath(img)
                        };
                        listImages.Add(itemImage);

                    }

                    execute.Insert_tblImages(listImages);
                    if (execute._error.Count > 0)
                    {
                        showMessage(execute._error);
                        return;
                    }
                }

            MessageBox.Show("Saved");
        }

        private void showMessage(List<Error> error)
        {
            foreach (Error err in error)
                MessageBox.Show(err.Messege, err.Proccess);
        }

        private string CopyImage(string copyPath)
        {
            copyPath = copyPath.Replace("/", @"\");

            string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            DateTime dtDateFormat = DateTime.Parse(this.btnTitle.Text.ToString());
            if (!Directory.Exists(@"Images\" + dtDateFormat.ToString("yyyy-MM-dd")))
                Directory.CreateDirectory(@"Images\" + dtDateFormat.ToString("yyyy-MM-dd"));

            string NewPath = string.Empty;

            NewPath = @"Images\" + dtDateFormat.ToString("yyyy-MM-dd") + @"\" + System.IO.Path.GetFileNameWithoutExtension(copyPath) + System.IO.Path.GetExtension(copyPath);

            if (copyPath.EndsWith(NewPath))
                return NewPath;

            for (int i = 0; i < 50; i++)
            {
                NewPath = @"Images\" + dtDateFormat.ToString("yyyy-MM-dd") + @"\" + System.IO.Path.GetFileNameWithoutExtension(copyPath) + i.ToString() + System.IO.Path.GetExtension(copyPath);
                if (!File.Exists(NewPath))
                    break;
            }


            File.Copy(copyPath, path + @"\" + NewPath);

            return NewPath;

        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {

            if (MessageBoxResult.No == MessageBox.Show("wont delete this diary day?", "", MessageBoxButton.YesNo, MessageBoxImage.Warning))
            {
                return;
            }

            DateTime dtDateFormat = DateTime.Parse(this.btnTitle.Text.ToString());



            var execute = new DB.Execute();

            if (isEdit)
            {
                DataSet ds = execute.Select_tblBody(dtDateFormat);

                foreach (DataTable dt in ds.Tables)
                    foreach (DataRow dr in dt.Rows)
                    {
                        execute.Delete_tblDiary(dr["Id"].ToString());
                        if (execute._error.Count > 0)
                        {
                            showMessage(execute._error);
                            return;
                        }
                        execute.Delete_tblImage(dr["Id"].ToString());
                        if (execute._error.Count > 0)
                        {
                            showMessage(execute._error);
                            return;
                        }
                    }
            }

            try
            {
                if (Directory.Exists(string.Format("Images/{0}", dtDateFormat.ToString("yyyy-MM-dd"))))
                    Directory.Delete(string.Format("Images/{0}", dtDateFormat.ToString("yyyy-MM-dd")), true);
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.Message);
            }

            this.Close();

        }

        private void lstImage_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                if(lstImage.SelectedIndex>=0)
                lstImage.Items.RemoveAt(lstImage.SelectedIndex);
            }
        }

        /// <summary>
        /// get settings
        /// </summary>
        private void GetSettings()
        {

            DB.Execute execute = new DB.Execute();
            DataSet ds = execute.Select_tblSettings();
            foreach (DataTable dt in ds.Tables)
                foreach (DataRow dr in dt.Rows)
                    if (dr["Id"].ToString().ToUpper().Equals("COLOR"))
                        Settings.color = dr["value"].ToString();

            this.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(Settings.color));
        }
    }
}
